/**
 * 路由状态观察者模式实现
 * 用于监听路由变化并通知相关组件更新状态
 */

// 观察者接口
class Observer {
  update(routeInfo) {
    throw new Error('Observer must implement update method')
  }
}

// 具体观察者：导航状态观察者
export class NavigationObserver extends Observer {
  constructor(name, callback) {
    super()
    this.name = name
    this.callback = callback
  }

  update(routeInfo) {
    console.log(`[${this.name}] Route changed:`, routeInfo)
    if (this.callback) {
      this.callback(routeInfo)
    }
  }
}

// 具体观察者：页面标题观察者
export class PageTitleObserver extends Observer {
  constructor() {
    super()
    this.titleMap = {
      '/': '用户登录 - 京东医疗',
      '/home': '首页 - 京东医疗',
      '/knowledge': '知识库 - 京东医疗',
      '/appointment': '预约挂号 - 京东医疗',
      '/about': '关于我们 - 京东医疗',
      '/my-appointments': '我的预约 - 京东医疗'
    }
  }

  update(routeInfo) {
    const title = this.titleMap[routeInfo.path] || 
                  `${routeInfo.name || '页面'} - 京东医疗`
    document.title = title
    console.log(`[PageTitle] Title updated: ${title}`)
  }
}

// 具体观察者：面包屑导航观察者
export class BreadcrumbObserver extends Observer {
  constructor(updateCallback) {
    super()
    this.updateCallback = updateCallback
    this.breadcrumbMap = {
      '/': [{ name: '登录', path: '/' }],
      '/home': [{ name: '首页', path: '/home' }],
      '/knowledge': [
        { name: '首页', path: '/home' },
        { name: '知识库', path: '/knowledge' }
      ],
      '/appointment': [
        { name: '首页', path: '/home' },
        { name: '预约挂号', path: '/appointment' }
      ],
      '/about': [
        { name: '首页', path: '/home' },
        { name: '关于我们', path: '/about' }
      ],
      '/my-appointments': [
        { name: '首页', path: '/home' },
        { name: '我的预约', path: '/my-appointments' }
      ]
    }
  }

  update(routeInfo) {
    const breadcrumbs = this.breadcrumbMap[routeInfo.path] || [
      { name: '首页', path: '/home' },
      { name: routeInfo.name || '页面', path: routeInfo.path }
    ]
    
    if (this.updateCallback) {
      this.updateCallback(breadcrumbs)
    }
    console.log(`[Breadcrumb] Updated:`, breadcrumbs)
  }
}

// 具体观察者：用户状态观察者
export class UserStateObserver extends Observer {
  constructor(userStore) {
    super()
    this.userStore = userStore
    this.publicRoutes = ['/', '/about']
  }

  update(routeInfo) {
    // 检查用户认证状态
    if (!this.publicRoutes.includes(routeInfo.path)) {
      const token = localStorage.getItem('token') || sessionStorage.getItem('token')
      if (!token && routeInfo.path !== '/') {
        console.log(`[UserState] Unauthorized access to ${routeInfo.path}, redirecting to login`)
        // 可以触发重定向逻辑
        this.userStore?.setRedirectPath(routeInfo.path)
      }
    }
  }
}

// 具体观察者：缓存管理观察者
export class CacheObserver extends Observer {
  constructor() {
    super()
    this.cacheKeys = new Set()
  }

  update(routeInfo) {
    // 根据路由变化管理缓存
    switch (routeInfo.path) {
      case '/knowledge':
        this.preloadKnowledgeCache()
        break
      case '/appointment':
        this.preloadDepartmentCache()
        break
      case '/home':
        this.preloadHomeCache()
        break
      default:
        this.cleanupUnusedCache()
    }
  }

  preloadKnowledgeCache() {
    console.log('[Cache] Preloading knowledge cache')
    // 预加载知识库相关缓存
  }

  preloadDepartmentCache() {
    console.log('[Cache] Preloading department cache')
    // 预加载科室相关缓存
  }

  preloadHomeCache() {
    console.log('[Cache] Preloading home cache')
    // 预加载首页相关缓存
  }

  cleanupUnusedCache() {
    console.log('[Cache] Cleaning up unused cache')
    // 清理不需要的缓存
  }
}

// 主题（被观察者）：路由状态管理器
export class RouteStateSubject {
  constructor() {
    this.observers = new Set()
    this.currentRoute = null
    this.routeHistory = []
  }

  // 添加观察者
  addObserver(observer) {
    if (!(observer instanceof Observer)) {
      throw new Error('Observer must extend Observer class')
    }
    this.observers.add(observer)
    console.log(`[RouteSubject] Observer added, total: ${this.observers.size}`)
  }

  // 移除观察者
  removeObserver(observer) {
    this.observers.delete(observer)
    console.log(`[RouteSubject] Observer removed, total: ${this.observers.size}`)
  }

  // 通知所有观察者
  notifyObservers(routeInfo) {
    console.log(`[RouteSubject] Notifying ${this.observers.size} observers`)
    this.observers.forEach(observer => {
      try {
        observer.update(routeInfo)
      } catch (error) {
        console.error(`[RouteSubject] Observer update failed:`, error)
      }
    })
  }

  // 路由变化处理
  onRouteChange(to, from) {
    const routeInfo = {
      path: to.path,
      name: to.name,
      fullPath: to.fullPath,
      params: to.params,
      query: to.query,
      meta: to.meta,
      timestamp: Date.now(),
      from: from ? {
        path: from.path,
        name: from.name
      } : null
    }

    // 更新当前路由和历史记录
    this.currentRoute = routeInfo
    this.routeHistory.push(routeInfo)
    
    // 保持历史记录在合理范围内
    if (this.routeHistory.length > 50) {
      this.routeHistory = this.routeHistory.slice(-30)
    }

    // 通知所有观察者
    this.notifyObservers(routeInfo)
  }

  // 获取当前路由信息
  getCurrentRoute() {
    return this.currentRoute
  }

  // 获取路由历史
  getRouteHistory() {
    return [...this.routeHistory]
  }

  // 获取观察者数量
  getObserverCount() {
    return this.observers.size
  }
}

// 单例模式：全局路由观察者管理器
class RouteObserverManager {
  constructor() {
    if (RouteObserverManager.instance) {
      return RouteObserverManager.instance
    }
    
    this.subject = new RouteStateSubject()
    this.router = null
    this.initialized = false
    
    RouteObserverManager.instance = this
  }

  // 初始化路由监听
  init(router) {
    if (this.initialized) {
      console.warn('[RouteObserverManager] Already initialized')
      return
    }

    this.router = router
    
    // 注册路由守卫
    router.beforeEach((to, from, next) => {
      console.log(`[RouteObserverManager] Route changing: ${from.path} -> ${to.path}`)
      next()
    })

    router.afterEach((to, from) => {
      this.subject.onRouteChange(to, from)
    })

    this.initialized = true
    console.log('[RouteObserverManager] Initialized with router')
  }

  // 添加观察者
  addObserver(observer) {
    return this.subject.addObserver(observer)
  }

  // 移除观察者
  removeObserver(observer) {
    return this.subject.removeObserver(observer)
  }

  // 获取当前路由信息
  getCurrentRoute() {
    return this.subject.getCurrentRoute()
  }

  // 获取路由历史
  getRouteHistory() {
    return this.subject.getRouteHistory()
  }

  // 手动触发路由状态更新（用于测试）
  triggerUpdate(routeInfo) {
    this.subject.notifyObservers(routeInfo)
  }
}

// 导出单例实例
export const routeObserverManager = new RouteObserverManager()

// 便捷的观察者工厂函数
export const createRouteObserver = {
  // 创建导航观察者
  navigation: (name, callback) => new NavigationObserver(name, callback),
  
  // 创建页面标题观察者
  pageTitle: () => new PageTitleObserver(),
  
  // 创建面包屑观察者
  breadcrumb: (updateCallback) => new BreadcrumbObserver(updateCallback),
  
  // 创建用户状态观察者
  userState: (userStore) => new UserStateObserver(userStore),
  
  // 创建缓存观察者
  cache: () => new CacheObserver(),

  // 创建自定义观察者
  custom: (updateFn) => {
    return new class extends Observer {
      update(routeInfo) {
        updateFn(routeInfo)
      }
    }()
  }
}